package cn.pugle.base.encrypt;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;

/**
 * @author tzp
 * @since 2018/3/6
 */
public class RSATest {
    public static void main(String[] args) throws Exception {
        // generate public and private keys
        KeyPair keyPair = buildKeyPair();
        PublicKey pubKey = keyPair.getPublic();
        PrivateKey priKey = keyPair.getPrivate();

        System.out.println(Hex.encodeHexString(pubKey.getEncoded()));
        System.out.println(Base64.encodeBase64String(pubKey.getEncoded()));//这个科学

        System.out.println(Hex.encodeHexString(priKey.getEncoded()));
        System.out.println(Base64.encodeBase64String(priKey.getEncoded()));

        //私钥加密 公钥解密
        byte[] encrypted = encrypt(priKey, "a");
        System.out.println(Base64.encodeBase64String(encrypted));  // <<encrypted message>>
        byte[] secret = decrypt(pubKey, encrypted);
        System.out.println(new String(secret));     // This is a secret message

        //公钥解密 私钥加密
        byte[] encrypted1 = encrypt(pubKey, "a");
        System.out.println(Base64.encodeBase64String(encrypted1));  // <<encrypted message>>
        byte[] secret1 = decrypt(priKey, encrypted1);
        System.out.println(new String(secret1));     // This is a secret message
    }

    public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {
        final int keySize = 2048;
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.genKeyPair();
    }


    public static byte[] encrypt(Key key, String message) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        return cipher.doFinal(message.getBytes());
    }

    public static byte[] decrypt(Key key, byte[] encrypted) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);

        return cipher.doFinal(encrypted);
    }


}
